<html>
<head>
    <title>OncoVis Prototype</title>
    <link rel="stylesheet" type="text/css" href="https://informatics-apps.systemsbiology.net/bootstrap-2.0.4/css/bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" href="https://informatics-apps.systemsbiology.net/jquery-ui-1.8.23/css/ui-lightness/jquery-ui-1.8.23.custom.css"/>
    <link rel="stylesheet" type="text/css" href="css/stylesheet.css"/>

    <script type="text/javascript" src="https://informatics-apps.systemsbiology.net/jquery-ui-1.8.23/js/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="https://informatics-apps.systemsbiology.net/jquery-ui-1.8.23/js/jquery-ui-1.8.23.custom.min.js"></script>

    <script type="text/javascript" src="https://informatics-apps.systemsbiology.net/bootstrap-2.1.1/js/bootstrap.min.js"></script>

    <script type="text/javascript" src="https://informatics-apps.systemsbiology.net/underscore/underscore-min.js"></script>
    <script type="text/javascript" src="https://informatics-apps.systemsbiology.net/d3js-2.9.7/d3.v2.min.js"></script>

    <script type="text/javascript" src="https://informatics-apps.systemsbiology.net/jquery-bbq/jquery.ba-bbq.js"></script>

    <script type="text/javascript" src="js/controls/dataRangeSlider.js"></script>
    <script type="text/javascript" src="js/controls/oncovisSlider.js"></script>
    <script type="text/javascript" src="js/controls/listControl.js"></script>
    <script type="text/javascript" src="js/controls/progressBar.js"></script>
    <script type="text/javascript" src="js/data.js"></script>
    <script type="text/javascript" src="js/oncovis.js"></script>
    <script type="text/javascript" src="js/legend.js"></script>
    <script type="text/javascript" src="js/filetree.js"></script>
    <script type="text/javascript">
        var PatientsByCluster = {};
        var MutatedPatientsByGene = {};
        var SearchListings = { files: [] };

        $(window).load(function () {
            $(window).filter_data_service({ "service": "/oncovis_prototype_svc/py-svcs/filter_by_genes.py" });

            $(window).bind('hashchange', function (e) {
                var data_address = e.fragment;
                if (data_address && data_address.indexOf("data:") == 0) {
                    Visualize(data_address.substring(data_address.indexOf("data:") + "data:".length));
                }
            });

            $.ajax({
                url:"data/all_genes_list.txt",
                method:"GET",
                success:function (txt) {
                    $("#gene_add_input").typeahead({ "source":_.rest(txt.split("\n"), 1) });
                }
            });

            $.ajax({ url:"data/search_listings.txt", method:"GET", success:function (txt) { SearchListings.files = txt.split("\n"); } });

            $.ajax({
                url: "data/oncovis_datamodel.json",
                method: "GET",
                success: function(json) {
                    if (json) {
                        _.each(json["clusters"], function(f) {
                            $("#clusters_data_menu").append('<li><a href="#" data-source="' + f.uri + '" onclick="return false;">' + f.label + '</a></li>');
                        });
                        _.each(json["mutations"], function(f) {
                            $("#mutations_data_menu").append('<li><a href="#" data-source="' + f.uri + '" onclick="return false;">' + f.label + '</a></li>');
                        });
                        _.each(json["copy_number"], function(f) {
                            $("#copynumber_data_menu").append('<li><a href="#data:' + f.uri + '">' + f.label + '</a></li>');
                        });

                        $("#clusters_data_menu").find("a").click(function(e) {
                            LoadedData = {};
                            PatientsByCluster = {};
                            $.ajax({
                                url: $(e.target).data("source"),
                                method:"GET",
                                success:function(txt) {
                                    ExtractPatientsByCluster(txt);
                                    $(window).trigger("hashchange");
                                },
                                error: function() {
                                    $("#cluster_list").empty();
                                    $(window).trigger("hashchange");
                                }
                            });
                        });

                        $("#mutations_data_menu").find("a").click(function(e) {
                            LoadedData = {};
                            $.ajax({
                                url: $(e.target).data("source"),
                                method:"GET",
                                success:function(txt) {
                                    ExtractMutatedPatientsByGene(txt);
                                    $(window).trigger("hashchange");
                                }
                            });
                        });

                    }
                }
            });

            $.when( $.ajax({ url:"data/clusters/gbm_subtypes.txt", method:"GET", success:ExtractPatientsByCluster }),
                    $.ajax({ url:"data/mutations/nonsilent_mutations.txt", method:"GET", success:ExtractMutatedPatientsByGene }),
                    $("#gene_list").listcontrol({ "url":"data/gene_list.txt", "storageId":"genes", "removableItems":true })
                  ).done(function(){ $(window).trigger('hashchange'); });

            $(".sortable_list ul, li").disableSelection();

            $("#legend").vislegend(
                    [
                        { label:'Amplification', cls:'amplification' },
                        { label:'Gain', cls:'gain' },
                        { label:'Diploid', cls:'diploid' },
                        { label:'Heterozygous Deletion', cls:'hetez_del' },
                        { label:'Homozygous Deletion', cls:'homoz_del' },
                        { label:'Mutation', cls:'mutation' }
                    ], { plot_height:140, plot_width:160 }
            );

            $("#gene_list").sortable({ revert:true, update:UpdateVisualization });
            $("#gene_list").sortable({
                revert:true,
                update:function() {
                    $("#gene_list").save_items();
                    UpdateVisualization();
                }
            });
            $("#gene_list").on("removed-item removed-items", function () {
                $("#gene_list").save_items();
                ReloadData();
            });

            $("#cluster_list").listcontrol();
            $("#cluster_list").sortable({ revert:true, update:UpdateVisualization });

            var datarangeFn = function(spanCls) {
                return function(values) {
                    $("." + spanCls).html(values.display);
                    UpdateVisualization();
                }
            };

            $("#slider_A").datarange({ min:-2, max:-1, slide: datarangeFn("span_A") });
            $("#slider_B").datarange({ min:-1, max:0, slide: datarangeFn("span_B") });
            $("#slider_C").datarange({ min:0, max:1, slide: datarangeFn("span_C") });
            $("#slider_D").datarange({ min:1, max:2, slide: datarangeFn("span_D") });

            var visrangeFn = function(property) {
                return function(value) {
                    var dim = {};
                    dim[property] = value;
                    _.each(LoadedData, function (visdata) {
                        $("#" + ContainersByDataId[visdata.id]).update(dim);
                    });
                }
            };
            $("#slider_barheight").oncovis_range({ min: 10, max: 50, initialStep: 20, slide: visrangeFn("bar_height") });
            $("#slider_rowspacing").oncovis_range({ min: 0, max: 50, initialStep: 10, slide: visrangeFn("row_spacing") });
            $("#slider_barwidth").oncovis_range({ min: 1, max: 10, initialStep: 5, slide: visrangeFn("bar_width") });
            $("#slider_barspacing").oncovis_range({ min: 0, max: 10, initialStep: 2, slide: visrangeFn("column_spacing") });
            $("#slider_clusterspacing").oncovis_range({ min: 0, max: 50, initialStep: 10, slide: visrangeFn("cluster_spacing") });
            $("#slider_fontsize").oncovis_range({ min: 5, max: 21, initialStep: 14, slide: visrangeFn("label_fontsize") });
        });

        function ExtractPatientsByCluster(txt) {
            $("#cluster_list").empty();

            var lines = txt.split("\n");
            var patients = lines[0].split("\t");
            var clusters = lines[1].split("\t");
            _.each(clusters, function (element, idx) {
                if (idx > 0) {
                    var cluster = element.trim();
                    var patient = patients[idx];
                    if (cluster && patient) {
                        if (!PatientsByCluster[cluster]) {
                            PatientsByCluster[cluster] = [];
                        }

                        $("#cluster_list").add_item(cluster);

                        PatientsByCluster[cluster].push(patient);
                    }
                }
            });
        }

        function ExtractMutatedPatientsByGene(txt) {
            var lines = txt.split("\n");
            var samples = lines[0].split("\t");
            _.each(_.rest(lines, 1), function(line) {
                var lineitems = line.split("\t");
                var gene = lineitems[0];
                if (gene) {
                    gene = gene.replace("_nonsilent", "").trim();
                    var samplesArray = [];
                    _.each(_.rest(lineitems, 1), function(value, idx) { if (value != 0) samplesArray.push(samples[idx]); });
                    if (samplesArray.length) MutatedPatientsByGene[gene] = samplesArray;
                }
            });
        }

        function AddGene() {
            var inputField = $("#gene_add_input")[0];
            var newitem = inputField.value;
            inputField.value = "";

            if ($("#gene_list").add_item(newitem)) {
                $("#gene_list").save_items();
                ReloadData();
            }
        }

        function BrowseData() {
            $('#browse_data').filetree('data/tcga', {
                service:'/oncovis_prototype_svc/py-svcs/list_files.py',
                breadcrumb:"#browse_breadcrumb"
            });
            $("#browse_data").on("filetree-loaded", function() {
                $('#modal_browse_file').modal('show');
                $("#browse_data a").click(function() {
                    $('#modal_browse_file').modal('hide');
                });
            });
        }

        function SearchData() {
            $('#search_data').typeahead({
                source:function () {
                    var files = [];
                    _.each(SearchListings.files, function (file) {
                        if (files.length <= 100 && files.indexOf(file) < 0) {
                                var queryterms = this.query.split(" ");
                                var passcount = 0;
                                _.each(queryterms, function(q) {
                                    if (file.toLowerCase().indexOf(q.toLowerCase()) >= 0) passcount += 1;
                                });
                                if (passcount >= queryterms.length) files.push(file);
                        }
                    }, this);

                    var fileselem = _.map(files, function(fileuri) {
                        return '<li id="' + fileuri + '"><a href="#data:'+ fileuri + '">' + fileuri + '</a></li>';
                    });
                    $("#search_results").empty();
                    $("#search_results").append(fileselem.join(""));
                    $("#search_results li").click(function() {
                        $('#modal_search_file').modal('hide');
                    });
                    return [];
                }
            });
            $('#modal_search_file').modal('show');
        }

        function ResetDataRangeSliders() {
            $("#slider_A").datarange_reset();
            $("#slider_B").datarange_reset();
            $("#slider_C").datarange_reset();
            $("#slider_D").datarange_reset();
        }

        function ResetLayoutSliders() {
            $("#slider_barheight").oncovis_range_reset();
            $("#slider_rowspacing").oncovis_range_reset();
            $("#slider_barwidth").oncovis_range_reset();
            $("#slider_barspacing").oncovis_range_reset();
            $("#slider_clusterspacing").oncovis_range_reset();
            $("#slider_fontsize").oncovis_range_reset();
        }
    </script>

</head>
<body>
<div class="wrapper">
    <div id="banner">
        <img src="images/banner.png" alt="Cancer Regulome"/>
    </div>

    <div class="navbar">
        <div class="navbar-inner">
            <div class="container">
                <div class="nav-collapse">
                    <ul class="nav">
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Data <b class="caret"></b></a>
                            <ul class="dropdown-menu">
                                <li><a href="#" onclick="BrowseData(); return false;">Browse...</a></li>
                                <li><a href="#" onclick="SearchData(); return false;">Search...</a></li>
                            </ul>
                        </li>
                        <li class="divider-vertical"></li>
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Copy Number <b class="caret"></b></a>
                            <ul id="copynumber_data_menu" class="dropdown-menu">
                                <li><a href="#data:data/copy_number/focal_data_by_genes.txt">Focal Data</a></li>
                                <li><a href="#data:data/copy_number/all_data_by_genes.txt">All Data</a></li>
                            </ul>
                        </li>
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Clusters <b class="caret"></b></a>
                            <ul id="clusters_data_menu" class="dropdown-menu">
                                <li><a href="#" data-source="data/clusters/gbm_subtypes.txt" onclick="return false;">GBM Sub-types</a></li>
                            </ul>
                        </li>
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Mutations <b class="caret"></b></a>
                            <ul id="mutations_data_menu" class="dropdown-menu">
                                <li><a href="#" data-source="data/mutations/nonsilent_mutations.txt" onclick="return false;">Non-Silent Mutations</a></li>
                            </ul>
                        </li>
                        <li class="divider-vertical"></li>
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Controls <b class="caret"></b></a>
                            <ul class="dropdown-menu">
                                <li><a href="#" onclick="$('#modal_controls_genelist').modal('show'); return false;">Gene List</a></li>
                                <li><a href="#" onclick="$('#modal_controls_clusterlist').modal('show'); return false;">Cluster List</a></li>
                                <li><a href="#" onclick="$('#modal_controls_dataranges').modal('show'); return false;">Data Ranges</a></li>
                                <li><a href="#" onclick="$('#modal_controls_vis').modal('show');  return false;">Visualization</a></li>
                            </ul>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <div>
        <ul id="data_vis_tabs" class="nav nav-tabs">
            <li class="dropdown">
                <a class="dropdown-toggle" id="drop4" role="button" data-toggle="dropdown" href="#">Legend <b class="caret"></b></a>
                <div id="legend" class="dropdown-menu well" role="menu" aria-labelledby="drop4"></div>
            </li>
        </ul>
        <div id="progress"></div>
        <div id="data_vis" class="tab-content"></div>
    </div>

    <div id="modal_controls_genelist" class="modal hide fade">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
            <h3>Gene List</h3>
        </div>
        <div id="sortable_genes" class="modal-body">
            <ul id="gene_list" class="sortable_list"></ul>
            <div class="well">
                <h4>Add Gene</h4>
                <input id="gene_add_input" type="text"/>
                <button onclick="AddGene();">+</button>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn" onclick="$('#gene_list').reset_items();">Reset</button>
            <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        </div>
    </div>

    <div id="modal_controls_clusterlist" class="modal hide fade">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
            <h3>Cluster List</h3>
        </div>
        <div id="sortable_clusters" class="modal-body">
            <ul id="cluster_list" class="sortable_list"></ul>
        </div>
        <div class="modal-footer">
            <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        </div>
    </div>

    <div id="modal_controls_dataranges" class="modal" style="display:none;">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
            <h3>Data Ranges</h3>
        </div>
        <div id="sliders_data" class="modal-body">
            <strong>Homozygous Deletion</strong>
            <br/>less than <span class="span_A">-1.5</span>
            <br/>
            <br/>

            <div id="slider_A"></div>
            <br/>
            <strong>Heterozygous Deletion</strong>
            <br/>between <span class="span_A">-1.5</span> and <span class="span_B">0.5</span>
            <br/>
            <br/>

            <div id="slider_B"></div>
            <br/>
            <strong>Diploid</strong>
            <br/>between <span class="span_B">-1.5</span> and <span class="span_C">0.5</span>
            <br/>
            <br/>

            <div id="slider_C"></div>
            <br/>
            <strong>Gain</strong>
            <br/>between <span class="span_C">0.5</span> and <span class="span_D">1.5</span>
            <br/>
            <br/>

            <div id="slider_D"></div>
            <br/>
            <strong>Amplification</strong>
            <br/>greater than <span class="span_D">1.5</span>
        </div>
        <div class="modal-footer">
            <button class="btn" onclick="ResetDataRangeSliders();">Reset</button>
            <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        </div>
    </div>

    <div id="modal_browse_file" class="modal" style="display:none;">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
            <h3>Browse...</h3>
            <ul id="browse_breadcrumb" class="breadcrumb"></ul>
        </div>
        <div id="browse_data" class="modal-body"></div>
        <div class="modal-footer">
            <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        </div>
    </div>

    <div id="modal_search_file" class="modal" style="display:none;">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
            <h3>Search...</h3>
        </div>
        <div class="modal-body">
            <input type="text" id="search_data"/>
            <ul id="search_results" class='nav nav-list'>
            </ul>
        </div>
        <div class="modal-footer">
            <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        </div>
    </div>

    <div id="modal_controls_vis" class="modal" style="display:none;">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
            <h3>Visualization</h3>
        </div>
        <div id="sliders_vis" class="modal-body">
            <strong>Bar Height</strong>

            <div id="slider_barheight"></div>
            <br/>

            <strong>Row Spacing</strong>

            <div id="slider_rowspacing"></div>
            <br/>

            <strong>Bar Width</strong>

            <div id="slider_barwidth"></div>
            <br/>

            <strong>Bar Spacing</strong>

            <div id="slider_barspacing"></div>
            <br/>

            <strong>Cluster Spacing</strong>

            <div id="slider_clusterspacing"></div>
            <br/>

            <strong>Label Font Size</strong>

            <div id="slider_fontsize"></div>
            <br/>
        </div>
        <div class="modal-footer">
            <button class="btn" onclick="ResetLayoutSliders();">Reset</button>
            <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        </div>
    </div>

    <div class="push"></div>
</div>
<div class="footer">
    <ul>
        <li><a href="http://cancergenome.nih.gov" target="_blank">The Cancer Genome Atlas</a></li>
        <li><a href="http://cancerregulome.org" target="_blank">Cancer Regulome Home</a></li>
        <li><a href="http://cancerregulome.googlecode.com" target="_blank">Open Source Project</a></li>
    </ul>
    &copy; 2012, <a href="http://systemsbiology.org" target="_blank">Institute for Systems Biology</a>, All Rights Reserved
</div>
</body>
</html>